const { app, BrowserWindow, Tray, Menu, nativeImage, globalShortcut, ipcMain } = require('electron');
const startServer = require('./server/bin/www');
const path = require('path');

const logoPath = path.join(__dirname, 'logo.png');

function createWindow() {
  startServer();
  const win = new BrowserWindow({
    width: 1000,
    height: 600,
    frame: false,
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true, // 让index页面中可以使用node
    },
  });
  win.menuBarVisible = false;
  win.setIcon(logoPath);
  // 快捷键注册
  globalShortcut.register('CommandOrControl+D', () => {
    win.webContents.openDevTools();
  });
  globalShortcut.register('CommandOrControl+R', () => {
    win.reload();
  });
  win.on('close', event => {
    event.preventDefault();
    win.hide();
  });
  // 自定义顶部栏的关闭、最大化最小化事件
  ipcMain.on('window-min', function () {
    win.minimize();
  })
  ipcMain.on('window-max', function () {
    if (win.isMaximized()) {
      win.restore();
    } else {
      win.maximize();
    }
  })
  ipcMain.on('window-close', function () {
    win.close();
  })

  win.loadFile('index.html');
  return win;
}

let tray = null;
const prepareTray = win => {
  tray = new Tray(logoPath);
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '退出应用',
      type: 'normal',
      click: () => {
        app.exit();
      },
    },
  ]);

  tray.setContextMenu(contextMenu);
  tray.setToolTip('待办工作台');
  tray.on('click', () => {
    win.show();
  });
};



app.whenReady().then(() => {
  const win = createWindow();
  prepareTray(win);
});

app.on('window-all-closed', function () {
  globalShortcut.unregisterAll();
  if (process.platform !== 'darwin') app.quit();
});
